import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import menus from "@/store/modules/menus";
import axios from "axios";


Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
		redirect:'/index_home',
        children: [
            {
                path: '/index_home',
                name: 'index_home',
                component: () => import('../views/indexView')
            },
            // {
            //     path: '/user',
            //     name: 'user',
            //     component: () => import('../views/t_wxUserInfo')
            // },
            // {
            //     path: '/message',
            //     name: 'message',
            //     component: () => import('../views/message')
            // },
            // {
            //     path: '/favorite',
            //     name: 'favorite',
            //     component: () => import('../views/favorite')
            // },
            // {
            //     path: '/organization',
            //     name: 'organization',
            //     component: () => import('../views/organization')
            // },
        ]
    },
    {
        path: '/Login',
        name: 'Login',
        component: () => import('../views/Login')
    },
]

const router = new VueRouter({
    // mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {   //from： 从哪来的， to:到那里去的， next:指定页面的跳转
    //验证token,只有存在token的时候，才能跳转到内容页
    // let token = localStorage.getItem("token"); //拿到token
    // let user = localStorage.getItem("user")
    // if (token || to.path === '/Login') {
    next()
    // } else {
    //     next('/Login')
    // }
    // 动态绑定路由
    let newRoutes = router.options.routes
    if (newRoutes[0].children.length <= 1 || menus.state.isGet === 1) {
        menus.state.menuList.forEach(menu => {
            if (menu.children) {
                menu.children.forEach(e => {
                    // 转成路由
                    let route = menuToRoute(e)
                    // 把路由添加到路由管理中
                    if (route) {
                        newRoutes[0].children.push(route)
                    }
                })
            }
        })
        router.addRoutes(newRoutes)
        menus.state.isGet = 0
    }

})

// 导航转成路由
const menuToRoute = (menu) => {
    if (!menu.component) {
        return null
    }
    let route = {
        name: menu.name,
        path: menu.path,
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    }
    route.component = () => import('@/views/' + menu.component)
    return route
}

export default router
